﻿using System;
using System.Net;
using System.IO;
using DotNet.Common.Kit;
using System.Data.OleDb;
using System.Data.Common;
namespace taobaoSpider
{
    public class Router
    {
        static LogerHelper logger = new LogerHelper(DirType.Local, MessageType.Exception);
        public static ShowErrorLogEventHandler ShowErrHandler = null;
        private static string GetWanPara(string htmlStr)
        {
            string ret = "";
            HtmlAgilityPack.HtmlNodeCollection hnc = GlobalFun.ParaseToHtml(htmlStr).DocumentNode.SelectNodes("//script");
            foreach (HtmlAgilityPack.HtmlNode node in hnc)
            {
                if (node.InnerText.Contains("wanPara"))
                {
                    string[] ipArr = node.InnerText.Split(',');
                    if (ipArr.Length > 2)
                        ret = ipArr[2].Trim();
                }
            }
            return ret;
        }
        /// <summary>
        /// 获取代理IP
        /// </summary>
        /// <param name="ipIndex"></param>
        /// <param name="ipCount"></param>
        /// <returns>对返回 "本机IP" 和 "" 要进行特处理</returns>
        public static string ProxyIp(ref int ipIndex,ref int ipCount,ref string vtime)
        {
            IniHelper ini = new IniHelper("HtmlNodeXPath.ini");
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            System.Windows.Forms.Label lblIpInfo = new System.Windows.Forms.Label();
            lblIpInfo.Name = "lblIpInfo";
            ShowErrorLogEventArgs e = new ShowErrorLogEventArgs();
            string retIp = "";
            string strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+System.Windows.Forms.Application.StartupPath+"\\taobaoInfo.mdb;Persist Security Info=False";
            try
            {
                DbHelper db = new DbHelper(strConn, "System.Data.OleDb");
                string strSql = "select *from proxyIp where useflag=1 order by vtime asc"; //保证使用最快的IP
                DbCommand cmd = db.GetSqlStringCommond(strSql) as OleDbCommand;
                System.Data.DataTable dt = db.ExecuteDataTable(cmd);
                ipCount = dt.Rows.Count;
                if (ipCount > 0)
                {
                    retIp = dt.Rows[ipIndex]["ip"].ToString();
                    item.UserAgent = "Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+.NET4.0C;+.NET4.0E;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.4506.2152;+.NET+CLR+3.5.30729)";
                    if (retIp == "本机IP")
                    {
                        item.ProxyIp = "";
                        //retIp = "";
                    }
                    else
                        item.ProxyIp = retIp;
                    
                    item.URL = ini.GetKeyValue("ProxyTestURL", "url");
                    string keyword=ini.GetKeyValue("ProxyTestURL", "keyword"); //访问页面的特征串。
                    item.Timeout = 9000;
                    string htmlStr = http.GetHtml(item).Html;
                    while (!htmlStr.Contains(keyword)) //没有得到验证串(自己服务器上面配置的串)
                    {
                        string delSql = "";
                        if (retIp.Contains("本机IP"))  //本机IP永不过期
                        {
                            delSql = "update proxyIp set useflag=1 where ip='" + retIp + "'";
                        }
                        else
                        {
                            delSql = "update proxyIp set useflag=0 where ip='" + retIp + "'";
                        }
                        cmd = db.GetSqlStringCommond(delSql) as OleDbCommand;
                        db.ExecuteNonQuery(cmd);
                        if (ipIndex < ipCount - 1)  
                            ipIndex++;
                        else    //大于了总数则退出while
                        {
                            break;
                        }
                        retIp = dt.Rows[ipIndex]["ip"].ToString();
                        //dt.Rows.RemoveAt(ipIndex);
                        item.ProxyIp = retIp;
                        //此处要调用显示IP信息this.ShowErrHandler(lblIpInfo, e);
                        e.ErrPosition = "Router:ProxyIp(ref p1,ref p2)==>while";
                        e.ErrMessage = "IP索引:" + ipIndex + "  代理IP：";
                        ShowErrHandler(lblIpInfo, e);
                        htmlStr = http.GetHtml(item).Html;
                    }
                    int useNum = Convert.ToInt32(dt.Select("ip='" + retIp + "'")[0]["usenum"]) + 1;
                    string updateSql = "update proxyIp set usenum=" + useNum + " where ip='" + retIp + "'";
                    string insertSql = "insert into proxytime(ip) values('" + retIp + "')";
                    cmd = db.GetSqlStringCommond(updateSql) as OleDbCommand;
                    db.ExecuteNonQuery(cmd);

                    cmd = db.GetSqlStringCommond(insertSql) as OleDbCommand;
                    db.ExecuteNonQuery(cmd);
                    logger.LogToFile("Router:ProxyIp()" + retIp);
                    //ipCount = dt.Rows.Count;
                    vtime = (Convert.ToDouble(dt.Rows[ipIndex]["vtime"])/1000).ToString();
                    return retIp;
                }
            }
            catch (Exception ex)
            {
                logger.WriteErrorLog(ex.StackTrace+ex.Message);
            }
            return retIp;
        }
        /// <summary>
        /// 更新IP访问的时间。
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="time"></param>
        public static void RefreshTime(string ip,long time)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "\\taobaoInfo.mdb;Persist Security Info=False";
            try
            {
                DbHelper db = new DbHelper(strConn, "System.Data.OleDb");
                string strSql = "select *from proxyIp where ip='" + ip + "'";
                DbCommand cmd = db.GetSqlStringCommond(strSql) as OleDbCommand;
                object obj=db.ExecuteScalar(cmd);
                if (obj != null)
                {
                    string updateSql = "update proxyIp set vtime=" + time + " where ip='" + ip + "'";
                    cmd = db.GetSqlStringCommond(updateSql) as OleDbCommand;
                    db.ExecuteNonQuery(cmd);
                }
                else
                {
                    if (ip.Contains("本机IP"))
                    {
                        string updateSql = "update proxyIp set vtime=" + time + " where ip='本机IP'";
                        cmd = db.GetSqlStringCommond(updateSql) as OleDbCommand;
                        db.ExecuteNonQuery(cmd);
                    }
                }
            }
            catch(Exception ex)
            {
                logger.WriteErrorLog(ex.StackTrace +"\r\n"+ ex.Message);
            }
        }
        public static string DisConnect()
        {
            //用户访问Router的用户名和密码
            string routerUserName = ReadIniFile.IniReadValue("Router", "username");
            string routerPwd = ReadIniFile.IniReadValue("Router", "pwd");
            string sDomain = "";
            //更新，断线 访问的URL，
            string disUrl = "http://192.168.1.1/userRpm/StatusRpm.htm?Disconnect=" + System.Web.HttpUtility.UrlEncode("断 线", System.Text.Encoding.GetEncoding("gb2312")) + "&wan=1";
            string reNewUrl = "http://192.168.1.1/userRpm/StatusRpm.htm?RenewIp=" + System.Web.HttpUtility.UrlEncode("更 新", System.Text.Encoding.GetEncoding("gb2312")) + "&wan=1";
            string renewIp = "";
            try
            {
                HttpHelper http = new HttpHelper();
                HttpItem item = new HttpItem();
                item.Referer = "http://192.168.1.1";
                item.Method = "GET";
                item.ContentType = "application/x-www-form-urlencoded";
                item.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6.4; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                item.Allowautoredirect = true;
                item.Credentials = new NetworkCredential(routerUserName, routerPwd, sDomain);

                item.URL = disUrl;
                string htmlStr = http.GetHtml(item).Html;
                renewIp = GetWanPara(htmlStr);
                while(renewIp.Contains("0.0.0.0"))
                {
                    System.Threading.Thread.Sleep(1000);
                    item.URL = reNewUrl;
                    htmlStr = http.GetHtml(item).Html;
                    renewIp = GetWanPara(htmlStr);
                }
            }
            catch (Exception ex)
            {
                GlobalFun.WriteExceptionLog(ex.StackTrace, ex.Message);
            }
            return renewIp;
        }

        public static void Dis()
        {
            string url = "断 线";
            string uri = "http://192.168.1.1/userRpm/StatusRpm.htm?Disconnect=" + System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.GetEncoding("gb2312")) + "&wan=1";
            string sUser = ReadIniFile.IniReadValue("Router", "username");
            string sPwd = ReadIniFile.IniReadValue("Router", "pwd");
            string sDomain = "";
            NetworkCredential oCredential;
            HttpWebRequest oRequest = (System.Net.HttpWebRequest)WebRequest.Create(uri);
            if (oRequest != null)
            {
                oRequest.ProtocolVersion = HttpVersion.Version11;// send request
                oRequest.Method = "GET";
                oRequest.ContentType = "application/x-www-form-urlencoded";
                oRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6.4; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                oRequest.Referer = "http://192.168.1.1";
                if (sUser != String.Empty)
                {
                    oCredential = new NetworkCredential(sUser, sPwd, sDomain);
                    oRequest.Credentials = oCredential.GetCredential(new Uri(uri), String.Empty);
                }
                else
                {
                    oRequest.Credentials = CredentialCache.DefaultCredentials;
                }
                try
                {
                    StreamReader sr = new StreamReader(oRequest.GetResponse().GetResponseStream(), System.Text.Encoding.Default);
                    string line = sr.ReadToEnd();
                    sr.Close();
                    //if (line.IndexOf("LAN口状态") > -1)//登录成功
                    //{
                    //    Console.WriteLine("断开登录成功");
                    //}
                    //else
                    //{
                    //    Console.WriteLine("断开登录失败");
                    //}
                }
                catch (Exception ex)
                {
                    System.Threading.Thread.Sleep(1000);
                    GlobalFun.WriteExceptionLog("Router:DisConnect():Exception", ex.Message);
                }
            }
        }
    }
}
